package com.lianchuang.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.lianchuang.httpclient.HttpClientUtil;

public class V6Util {
	
	public static String getUrl(String name) throws Exception{
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("show", "title,smalltext");
		param.put("tempid", "1");
		param.put("tbname", "Article");
		param.put("keyboard", name);
	
		String result = HttpClientUtil.post("http://www.6vhao.tv/e/search/index.php", param,"gb2312");
		if(result.contains("没有搜索")){//为查找到
			return "";
		}
		Document doc = Jsoup.parse(result);
		String urlSub = doc.getElementsByTag("a").get(0).attr("href");
		return "http://www.6vhao.tv/e/search/"+urlSub;
	}
	  public static void main(String[] args) throws Exception {
		System.out.println(getRes("天才枪手"));
	}
	public static String getRes(String name) {
		Document doc;
		try {
			String url = getUrl(name);
			if(url == null || "".equals(url)){
				return "";
			}
			doc = StaticResourceDownload.getDoc(url);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return "";
		}
		Elements eles = doc.getElementsByClass("listBox");
		Element pageEle = eles.get(0);
		Elements liEles = pageEle.getElementsByTag("li");
		Iterator<Element> liEleIter = liEles.iterator();
		StringBuffer sb = new StringBuffer("");
		int count = 0;
		while(liEleIter.hasNext()){
			try {
				count++;
				Element liEle = liEleIter.next();
				//获取子页面信息
				Element aEle = liEle.getElementsByTag("a").get(0);
				String subUrl = aEle.attr("href");
				Document docSub = StaticResourceDownload.getDoc(subUrl);
				Element ttext = docSub.getElementById("text");
				
				
				Element tableEle = ttext.getElementsByTag("table").get(0);//保存下载链接
				Elements subAElems = tableEle.getElementsByTag("a");
				Iterator<Element> eIteraa = subAElems.iterator();
				
				while(eIteraa.hasNext()){
					Element subA = eIteraa.next();
					String l = subA.attr("href");
					if(l.length() < 6){
						l = subA.attr("ypznorqe");
						
						if(l.length() < 6){
							l = subA.attr("jsmbvdzx");
						}
					}
					if(l.contains("pan.baidu.com")){
						l = subA.parent().text();
					}
					if(subA.text().startsWith("http")){
						continue;
					}
					//System.out.println(subA.text()+"====="+l);
					sb.append("片名:"+subA.text()+"\r\n"+"下载地址:"+l+"\r\n");
					if(sb.toString().length() > 1300){//避免超过微信长度限制
						break;
					}
				}
				break;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	
	}
}
